﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Elderos.Highlight.Search;
using Elderos.Ontology;
using Elderos.Utils.Extensions;

namespace Elderos.Highlight.Rules
{
    [RankingRule("SynonymFrequency", RuleType.Synonym)]
    public class RuleSynonymFrequency : RankingRule
    {
        public RuleSynonymFrequency(IOntologyData ontology) : base(ontology) {}

        protected async override Task<Dictionary<TextEntity, IRuleResult>> InnerRank(HighlightResult highlightResult)
        {
            var ruleResults = new Dictionary<TextEntity, IRuleResult>();

            var synonyms = 
                highlightResult
                .Positions
                .SelectMany(x => x.SubpositionsFlattened)
                .Select(x => x.Text)
                .ToArray();

            Dictionary<string, double> synonymFrequencies = await Ontology.GetSynonymFrequenciesAsync(synonyms);

            foreach (var position in highlightResult.Positions.SelectMany(x => x.SubpositionsFlattened))
            {
                string synonym = position.Text;
                if (!synonymFrequencies.ContainsKey(synonym)) continue;
                double frequency = synonymFrequencies[synonym];

                foreach (TextEntity textEntity in position.Entities)
                {
                    ruleResults.Add(textEntity, new ContiniousResult(Name, frequency));
                }
            }

            return ruleResults;
        }

        public override IRuleResult EmptyResult
        {
            get { return new ContiniousResult(Name, 0);}
        }
    }
}
